package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.LotterBuyHouseAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.LotterBuyHouseBean;
import com.weixin.paleituo.bean.OrderBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.LotterBuyHouseEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.YRecycleview;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 摇号购房
 */
public class LotteryBuyHouseActivity extends BasePersonActivity {


    @BindView(R.id.yrecycleview_activity_lottery_buy_house)
    YRecycleview mYrecycleviewActivityLotteryBuyHouse;
    @BindView(R.id.tv_submit_activity_lottery_buy_house)
    TextView mTvSubmitActivityLotteryBuyHouse;
    @BindView(R.id.rl_bottom_root_activity_lottery_buy_house)
    RelativeLayout mRlBottomRootActivityLotteryBuyHouse;


    private LoadingPagerHead mLoadingPagerHead;
    private LotterBuyHouseAdapter mLotterBuyHouseAdapter;
    List<LotterBuyHouseBean> mLotterBuyHouseBeans = new ArrayList<>();
    private int mCheckPosition;
    private Dialog mLoadingDialog;

    @Override
    protected View getContentView(Context context) {
        mLoadingPagerHead = new LoadingPagerHead(this,R.layout.layout_lottorhous_empty) {
            @Override
            protected void close() {

            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(LotteryBuyHouseActivity.this, R.layout.activity_lottery_buy_house);
            }
            @Override
            protected void reLoading() {
                retry();
            }
        };


     //   UIUtils.inflate(LotteryBuyHouseActivity.this, R.layout.activity_lottery_buy_house);


        return mLoadingPagerHead;
    }

    /**
     * 重新加载
     */
    private void retry() {

        String houseId = getIntent().getStringExtra(Contans.INTENT_DATA);
        String username = BaseApplication.sUserInfoBean.getUsername();

        Observable<StatusCode<List<LotterBuyHouseBean>>> observable = ApiUtils.getApi().getLotterBuyHouseList(username, houseId,BaseApplication.sUserInfoBean.getToken(),BaseApplication.sUserInfoBean.userId);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<LotterBuyHouseBean>>(this) {
            @Override
            protected void _onNext(StatusCode<List<LotterBuyHouseBean>> t) {

                List<LotterBuyHouseBean> lotterBuyHouseBeans = t.getData();
                if (lotterBuyHouseBeans!=null &&lotterBuyHouseBeans.size()>0){
                  // mTvTitle.setText(lotterBuyHouseBeans.get(0).getHouses()+"");
                    mLotterBuyHouseBeans.addAll(lotterBuyHouseBeans);
                    mLotterBuyHouseAdapter.notifyDataSetChanged();
                    mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                }else {
                    mLoadingPagerHead.showPagerView(Contans.STATE_EMPTY);
                }
            }

            @Override
            protected void _onError(String message) {
                mLotterBuyHouseBeans.clear();
                mLotterBuyHouseAdapter.notifyDataSetChanged();
                mLoadingPagerHead.showPagerView(Contans.STATE_EMPTY);

            }
        }, "", lifecycleSubject, false, true);

    }
    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText("摇号信息");
        EventBus.getDefault().register(this);
        mYrecycleviewActivityLotteryBuyHouse.setReFreshEnabled(false);
        mYrecycleviewActivityLotteryBuyHouse.setLoadMoreEnabled(false);
        mLotterBuyHouseBeans.clear();
        mLotterBuyHouseAdapter = new LotterBuyHouseAdapter(this, mLotterBuyHouseBeans);
        mYrecycleviewActivityLotteryBuyHouse.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mYrecycleviewActivityLotteryBuyHouse.setAdapter(mLotterBuyHouseAdapter);
        //设置Item增加、移除动画
        mYrecycleviewActivityLotteryBuyHouse.setItemAnimator(new DefaultItemAnimator());
        mLotterBuyHouseAdapter.setCurrentPosition(0);
        retry();
    }

    public static void startActivity(Context context, String houseid) {
        Intent intent = new Intent(context, LotteryBuyHouseActivity.class);
        intent.putExtra(Contans.INTENT_DATA, houseid);
        context.startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void checkitemtEvent(LotterBuyHouseEvent lotterBuyHouseEvent) {
//        mCheckPosition = lotterBuyHouseEvent.getCheckPosition();
//        mLotterBuyHouseAdapter.setCurrentPosition(mCheckPosition);
//        mLotterBuyHouseAdapter.notifyDataSetChanged();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }



    @OnClick(R.id.tv_submit_activity_lottery_buy_house)
    public void onMTvSubmitActivityLotteryBuyHouseClicked() {
        int housesId = mLotterBuyHouseBeans.get(mCheckPosition).getHousesId();
      final   int roomId = mLotterBuyHouseBeans.get(mCheckPosition).getRoomId();
        String userId = BaseApplication.getUserId();
        Observable observable = ApiUtils.getApi().createOrder(housesId + "", roomId + "", userId,"2",BaseApplication.sUserInfoBean.getToken()).compose(RxHelper.getObservaleTransformer())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                        if (mLoadingDialog == null) {
                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(LotteryBuyHouseActivity.this, "");
                        }
                        mLoadingDialog.show();

                    }
                }).subscribeOn(AndroidSchedulers.mainThread());
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderBean>(this) {

            @Override
            protected void _onNext(StatusCode<OrderBean> t) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                OrderBean orderBean = t.getData();
                if (orderBean!=null&&t.isFlag()){
                    OrdersActivity.startActivity(LotteryBuyHouseActivity.this,orderBean, roomId,2);
                    finish();
                }else {
                    ToastUtils.makeText(t.getDetailMsg()+"");
                }
            }
            @Override
            protected void _onError(String message) {
                ToastUtils.makeText(message);
                LoadingDialogUtils.closeDialog(mLoadingDialog);

            }
        },"",lifecycleSubject,false,true);

    }

    @OnClick(R.id.tv_anew_select_lotterbuyhouse_activity)
public void anewLookOnClick(){

finish();

}
}
